import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/values/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef ClickStart = Future<bool> Function();
typedef CountStr = String Function(int count);

///倒计时
class CommonCount extends StatefulWidget {
  const CommonCount({
    Key? key,
    required this.clickStart,
    this.startStrColor = AppColors.black,
    this.countStrColor = AppColors.textLevelThree,
    this.startStr = '获取验证码',
    this.countStr,
    this.maxCount = 60,
  }) : super(key: key);

  final String startStr;
  final Color startStrColor;
  final CountStr? countStr;
  final Color countStrColor;
  final int maxCount;
  final ClickStart clickStart;

  @override
  State<StatefulWidget> createState() => _CommonCountState();
}

class _CommonCountState extends State<CommonCount> {
  late int _curCount = widget.maxCount;
  late String text = widget.startStr;
  late Color fontColor = widget.startStrColor;
  Timer? timer;

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  bool isStart() => timer != null && timer!.isActive;

  void startCount() {
    if (isStart()) return;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_curCount > 1) {
        count();
      } else {
        end();
      }
    });
    count();
  }

  void count() {
    setState(() {
      _curCount--;
      text = widget.countStr == null ? '重新获取(${_curCount}s)' : widget.countStr!(_curCount);
      fontColor = widget.countStrColor;
    });
  }

  void end() {
    setState(() {
      text = widget.startStr;
      fontColor = widget.startStrColor;
      _curCount = widget.maxCount;
      timer?.cancel();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ButtonWidget.text(
      text,
      fontSize: 15,
      textColor: fontColor,
      hasInkWell: false,
      padding: EdgeInsets.all(5.w),
      onTap: () async {
        if (!isStart() && await widget.clickStart()) {
          startCount();
        }
      },
    );
  }
}
